#!/usr/bin/env python 
# coding: utf8 
from gluon.html import *
from gluon.http import *
from gluon.validators import *
from gluon.sqlhtml import *
# request, response, session, cache, T, db(s) 
# must be passed and cannot be imported!

import ply.lex as lex
import ply.yacc as yacc

def start_parser():
    tokens = (
        "WORD",
        "NUMBER",
        "PHRASE",
    )

    t_WORD = r'-?[a-zA-Z]+'
    t_NUMBER = r'[<>=-]?[0-9]+'
    t_PHRASE = r'-?"([a-zA-Z]+|[0-9]+)( ([a-zA-Z]+|[0-9])+)+"'

    t_ignore = ' \t\n\r'

    lexer = lex.lex()
    
    search_terms = None
    
    def p_search_w_term(p):
        '''search : search ' ' term'''
        search_terms = [p[1]]
        p[0] = None
        
    def p_search_term(p):
        '''search : term'''
        search_terms += p[1]
        p[0] = None
        
    def p_term_phrase(p):
        '''term : PHRASE
                | WORD
                | NUMBER'''
        p[0] = p[1]
        
    myparser = yacc.yacc()
    
    def input(text):
        result = myparser.parse(text, lexer=lexer)
        return result
        
    return input
